package com.transcargo.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import com.transcargo.errors.ErrorList;
import com.transcargo.db.db;
import com.transcargo.db.dbException;

public class AddContactAction extends AuthAction {

    private String name = "";
    private String phone1 = "";
    private String phone2 = "";
    private String phone3 = "";
    private String icq = "";
    private String skype = "";
    private String email = "";
    private String info = "";
    private String filename = "";
    private HashMap<String,String> params = new HashMap<String,String>();

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException, ServletException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) throw new ServletParametersException();

        try {
            // Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			factory.setSizeThreshold(1024*512);
			factory.setRepository(new File("WEB-INF/tmpfiles"));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			upload.setSizeMax(1024*520);

			// Parse the request
			List /* FileItem */ items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (item.isFormField()) {
			        String name = item.getFieldName();
			        String value = item.getString("UTF-8");
			        params.put(name,value);
			    } else {
			        String fieldName = item.getFieldName();
			        if (fieldName.equals("photo") && item.getSize() > 0) {
				        String contentType = item.getContentType();
				        InputStream uploadedStream = item.getInputStream();
				        String hash = "";
	                    Random rand = new Random();
		                Date dateS = new Date();
		                rand.setSeed(request.getRemotePort()*17600000 + dateS.getTime());
		                for (int j = 0; j < 24; j++) hash = hash + (char)('A' + rand.nextInt(26));
		                filename = hash;
		                if (contentType.equals("image/gif")) filename = filename + ".gif";
		                else if (contentType.equals("image/bmp")) filename = filename + ".bmp";
		                else if (contentType.equals("image/jpg")) filename = filename + ".jpg";
		                else if (contentType.equals("image/jpeg")) filename = filename + ".jpg";
		                else if (contentType.equals("image/tiff")) filename = filename + ".tiff";
		                else if (contentType.equals("image/png")) filename = filename + ".png";
		                else throw new ServletParametersException(ErrorList.ERROR_STR_INVALID_IMAGE_FORMAT);
		                FileOutputStream uploadedFile = new FileOutputStream("webapps" + getServletContext().getContextPath() + "/avatars/" + filename);
		                byte[] b = new byte[1024];
		                while (uploadedStream.available() > 0) {
		                	uploadedStream.read(b);
		                	uploadedFile.write(b);
		                }
				        uploadedStream.close();
				        uploadedFile.close();
                    }
			    }
			}
        }  catch (IOException e)
		{
			System.out.println("IOException exception: " + e.getMessage());
			e.printStackTrace(System.out);
            throw new ServletException("IO Exception in Servlet " + this.getServletName());

        } catch (FileUploadException e)
		{
			System.out.println("FileUpload exception: " + e.getMessage());
			e.printStackTrace(System.out);
            throw new ServletException("Upload Exception in Servlet " + this.getServletName());
        }

        name = params.get("name");
        phone1 = params.get("phone1");
        phone2 = params.get("phone2");
        phone3 = params.get("phone3");
        icq = params.get("icq");
        skype = params.get("skype");
        email = params.get("email");
        info = params.get("info");

        if (name == null) name = "";
        if (phone1 == null) phone1 = "";
        if (phone2 == null) phone2 = "";
        if (phone3 == null) phone3 = "";
        if (icq == null) icq = "";
        if (skype == null) skype = "";
        if (email == null) email = "";
        if (info == null) info = "";
    }

    private void servletValidateValues() throws ServletValidationException {
        if (name == null || name.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_NAME_MISSING);
            if (name.length() > 255) throw new ServletValidationException(ErrorList.ERROR_STR_NAME_TOO_LONG);
        if (phone1 == null || phone1.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_CELLPHONE_MISSING);
            if (phone1.length() > 24) throw new ServletValidationException(ErrorList.ERROR_STR_CELLPHONE_TOO_LONG);
        if (phone2.length() > 24) throw new ServletValidationException(ErrorList.ERROR_STR_CITYPHONE_TOO_LONG);
        if (phone3.length() > 24) throw new ServletValidationException(ErrorList.ERROR_STR_ALTPHONE_TOO_LONG);
        if (icq.length() > 64) throw new ServletValidationException(ErrorList.ERROR_STR_ICQ_TOO_LONG);
        if (skype.length() > 64) throw new ServletValidationException(ErrorList.ERROR_STR_SKYPE_TOO_LONG);
        if (info.length() > 255) throw new ServletValidationException(ErrorList.ERROR_STR_INFO_TOO_LONG);
    }

    private void servletExecuteAction() throws ServletActionException {
        try {
            db.PreStatement pre = dbase.CreateStatement("INSERT INTO contacts (user_id, name, phone1, phone2, phone3, email, icq, skype, info, photo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            pre.Insert(User_Id);
            pre.Insert(name);
            pre.Insert(phone1);
            pre.Insert(phone2);
            pre.Insert(phone3);
            pre.Insert(email);
            pre.Insert(icq);
            pre.Insert(skype);
            pre.Insert(info);
            pre.Insert(filename);
            dbase.executeUpdate(pre);
        } catch (SQLException e) {
			System.out.println("SQL exception: " + e.getMessage());
            e.printStackTrace(System.out);
			throw new ServletActionException();
		} catch (dbException e) {
			System.out.println("Database exception: " + e.getMessage());
            e.printStackTrace(System.out);
			throw new ServletActionException();
		}
    }

    public void processRequest(Boolean post, HttpServletRequest request, HttpServletResponse response) throws ServletException {
		if (!post) return;

		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "user.jsp?i=2");
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));

            } else {
                sendRedirect(response, "newcontact.jsp");
            }

        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
